package controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import pojo.entity.PageSupport;
import pojo.entity.SysRole;
import pojo.entity.SysUser;
import service.SysRoleService;
import service.SysUserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author 吴阳基
 * @datetime 2024/1/16 16:52
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private final Logger logger = Logger.getLogger(UserController.class);
    @Resource
    private SysUserService userService;
    @Resource
    private SysRoleService roleService;
    private final ArrayList<SysUser> sysUserList = new ArrayList<>();
    private final ArrayList<SysUser> queryUserList = new ArrayList<>();

    public UserController() {
        try {
            sysUserList.add(new SysUser(5, "zhangjing", "张静", "55555", 1, LocalDateTime.of(1998, 12, 4, 0, 0), "1301524758", "上海宝安区", 1, 1, LocalDateTime.now(), 1, LocalDateTime.now()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping(value = "/toLogin")
    public String Login() {
        logger.debug("跳转到登录页面");
        return "login";
    }

    /**
     * 登录验证，并跳转到主页面
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String doLogin(HttpServletRequest request,
                          HttpSession session,
                          @RequestParam String account,
                          @RequestParam String password) {

        logger.debug("用户登录");
        SysUser user = userService.login(account, password);
        if (user != null) {
            //将登录用户发到session
            session.setAttribute("userSession", user);
            //登录录成功，跳转到主页面
            return "redirect:/user/toMain";
        }

        request.setAttribute("msg", "用户名或密码错误");
        //用户户名或密码错误，跳转到登录页面重新登录
        return "login";
    }

    @RequestMapping(value = "/exLogin")
    public String exLogin(@RequestParam String account,
                          @RequestParam String password) {
        SysUser user = userService.login(account, password);
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        return "redirect:/user/toMain";
    }

    /**
     * 跳转到主页面
     * @return
     */
    @RequestMapping(value = "/toMain")
    public String main(HttpSession session) {
        if (session.getAttribute("userSession") == null) {
            return "redirect:/user/toLogin";
        }
        logger.debug("跳转到主页面");
        return "frame";

    }

    /**
     * 查询所有用户
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String list(Model model) {

        logger.info("当查询条件为空时，查询用户信息");
        queryUserList.clear();
        queryUserList.addAll(sysUserList);
        model.addAttribute("queryUserList", queryUserList);
        return "sysUser/sysUserList";
    }

    @GetMapping("/list")
    public String list(Model model,
                       String queryRealName,
                       Integer queryRoleId,
                       @RequestParam(defaultValue = "1") Integer pageIndex) {
        List<SysUser> userList = null;
        try {
            int pageSize = 5;
            int totalCount = userService.getUserCount(queryRealName, queryRoleId);
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();

            if (pageIndex > totalPageCount) {
                pageIndex = totalPageCount;
                throw new RuntimeException("页码超出范围");
            }

            userList = userService.getUserList(queryRealName, queryRoleId, pageIndex, pageSize);
            model.addAttribute("userList", userList);


            List<SysRole> roleList = null;
            roleList = roleService.getRoleList();
            model.addAttribute("roleList", roleList);
            model.addAttribute("queryRealName", queryRealName);
            model.addAttribute("queryRoleId", queryRoleId);
            model.addAttribute("totalPageCount", totalPageCount);
            model.addAttribute("totalCount", totalCount);
            model.addAttribute("currentPageNo", pageIndex);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";//跳转到用户列表页面，并将查询条件传递到页面中去。

    }

    @RequestMapping(value = "/toSysError")
    public String toSysError() {
        return "sysError";//跳转到系统错误页面。
    }

    @PostMapping("/list")
    public String list(@RequestParam(value = "realName", required = false) String realName, Model model) {
        logger.info("当查询条件不为空时，查询用户信息");
        queryUserList.clear();
        if (realName != null && !realName.equals("")) {
            for (SysUser sysUser : sysUserList) {
                if (sysUser.getRealName().indexOf(realName) != -1) {
                    queryUserList.add(sysUser);
                }
            }
        } else {
            queryUserList.addAll(sysUserList);
        }
        model.addAttribute("queryUserList", queryUserList);
        return "sysUser/sysUserList";
    }

    //@RequestMapping(value = "/view", method = RequestMethod.GET)
    @ResponseBody
    @GetMapping("/view/{id}")
    public String view(@PathVariable String id) {
        logger.info("根据id查看用户详情" + id);
        String sysUserJSON = "";
        if (null != id && !id.equals("")) {
            return "nodata";
        } else {
            try {
                SysUser sysUser = userService.getUserById(Integer.parseInt(id));
                sysUserJSON = JSON.toJSONString(sysUser);
                logger.debug("查询用户详情成功");
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("查询用户详情失败");
                return "failed";
            }
            return sysUserJSON;
        }


    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save() {
        logger.info("添加用户");
        return null;
    }

    public String handlerException(RuntimeException e, HttpServletRequest request) {
        request.setAttribute("e", e);
        return "error";
    }

    @GetMapping(value = "/add")
    public String toAdd(@ModelAttribute("sysUser") SysUser sysUser) {
        return "sysUser/add";//跳转到用户添加页面。
    }

    @PostMapping("/add")
    public String add(@Valid SysUser user, BindingResult bindingResult, HttpSession session) {
        if (bindingResult.hasErrors()) {
            logger.error("添加用户失败");
            return "sysUser/add";//跳转到用户添加页面。
        }

        user.setCreatedUserId(((SysUser) session.getAttribute("userSession")).getId());
        if (userService.add(user) > 0) {
            logger.info("添加用户成功");
            return "redirect:/user/list";//跳转到用户列表页面。
        }
        return "sysUser/add";//跳转到用户添加页面。
    }

    @GetMapping(value = "/toUpdate")
    public String toUpdate(@RequestParam String uid, Model model) {
        logger.debug("跳转到修改用户信息页面");
        SysUser sysUser = userService.getUserById(Integer.parseInt(uid));
        model.addAttribute(sysUser);
        return "sysUser/update";//跳转到用户修改页面。
    }

    @PostMapping("/update")
    public String update(SysUser user, HttpSession session) {
        logger.debug("修改用户信息");
        user.setUpdatedUserId(((SysUser) session.getAttribute("userSession")).getId());
        if (userService.update(user) > 0) {
            logger.info("修改用户成功");
            return "redirect:/user/list";//跳转到用户列表页面。
        }
        return "sysUser/update";//跳转到用户修改页面。
    }

    @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam String account) {
        logger.debug("验证用户名 account = " + account + "的用户是否存在");
        HashMap<String, Object> result = new HashMap<>();
        if (StringUtils.isNullOrEmpty(account)) {
            result.put("exist", 1);
        } else {
            SysUser sysUser = userService.getAccountExist(account);
            if (sysUser != null) {
                result.put("exist", 1);
            } else {
                result.put("exist", 0);
            }
        }

        return JSON.toJSONString(result);

    }
}
